package com.solocredit.finance.ui.loan.impl

import android.content.Context
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.http.ApiService
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.ApiService.addRandomParams
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.presenter.MvpPresenter
import com.solocredit.finance.ui.loan.view.IMullaLoanRepayView
import com.solocredit.finance.utils.DateUtils
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONArray
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/7 13:45
 * @Annotation：还款信息 Presenter 实现
 */
class MullaLoanRepayPresenterImpl(context: Context?) : MvpPresenter<IMullaLoanRepayView>(context) {

    //待还款信息
    var repayInfo: JSONObject? = null
    //优惠券列表
    private var couponList: ArrayList<JSONObject>? = null
    //选择的优惠券信息
    private var selectCoupon: JSONObject? = null

    /**
     * 选择优惠券
     */
    fun onMullaChooseCouponAction(){
        couponList?.let {
            mvpView?.showMullaUserCouponList(it)
        }
    }

    /**
     * 设置选择的优惠券
     */
    fun onMullaSetSelectCouponInfo(obj: JSONObject?){
        selectCoupon = obj
    }

    /**
     * 获取还款信息
     */
    fun loadMullaLoanRepayInfoAction(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_LOAN_REPAYMENT_INFO_PATH)
        val params = JSONObject().addCommonParams().addRandomParams()
        params.put("product",mvpView?.loadProductName())
        params.put("token",mvpView?.loadProductToken())
        HttpHelper.postMullaAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null) {
                            repayInfo = obj
                            mvpView?.showMullaRepayInfo(obj)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 获取优惠券列表
     */
    fun loadMullaUserCouponListAction(){
        if (couponList == null){
            couponList = arrayListOf()
        }
        couponList?.clear()
        val dataString = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_USER_COUPON_INFO)
        if (dataString.isNotEmpty()){
            val couponArray = JSONArray(dataString)
            if (couponArray.length() > 0){
                repayInfo?.let {
                    //待还金额
                    val repayAmount = it.optLong("repayAmount")
                    //到账金额
                    val receivedAmount = it.optLong("realAmount")
                    for (i in 0..< couponArray.length()){
                        val item = couponArray.optJSONObject(i)
                        val couponInfo = JSONObject(item.optString("couponInfo"))
                        //优惠券满足金额
                        val fullAmount = couponInfo.optLong("fullAmount")
                        //优惠券抵扣金额
                        val discountAmount = couponInfo.optLong("amount")
                        //待还金额 < 优惠券满足金额 -> 不可用
                        if (repayAmount < fullAmount){
                            item.put("isAvailable",false)
                            item.put("unavailableReason",MyApp.app.getString(R.string.coupon_use_dialog_unavailable_total))
                        } else {
                            //待还款金额 - 实际到账金额 < 优惠券抵扣金额  -> 不可用
                            if (repayAmount - receivedAmount < discountAmount){
                                item.put("isAvailable",false)
                                item.put("unavailableReason",MyApp.app.getString(R.string.coupon_use_dialog_unavailable_discount))
                            } else {
                                item.put("isAvailable",true)
                            }
                        }
                        val validitytTime = item.optLong("validitytTime") * 1000
                        item.put("expiresTime", DateUtils.getFormatTime(validitytTime,"dd/MM/yyyy"))
                        item.put("daysLeft",DateUtils.getDaysFromTimestamps(System.currentTimeMillis(),validitytTime))
                        couponList?.add(item)
                    }
                }
            }
        }

        couponList?.let {
            if (it.size > 0){
                var maxAmount = 0L
                for (i in 0..< it.size){
                    val item = it[i]
                    if (!item.optBoolean("isAvailable",false)){
                        continue
                    }
                    val couponInfo = JSONObject(item.optString("couponInfo"))
                    val amount = couponInfo.optLong("amount")
                    //筛选选出可用的最大金额
                    if (amount > maxAmount){
                        maxAmount = amount
                    }
                }

                for (i in 0..< it.size){
                    val item = it[i]
                    if (!item.optBoolean("isAvailable",false)){
                        continue
                    }
                    val couponInfo = JSONObject(item.optString("couponInfo"))
                    val amount = couponInfo.optLong("amount")
                    if (amount == maxAmount){
                        item.put("isSelect",true)
                        onMullaSetSelectCouponInfo(item)
                        break
                    }
                }
            }
        }
        mvpView?.showMullaDufauleUseCouponInfo(selectCoupon)
    }

    /**
     * 订单还款
     * 不减免 normal
     * 积分减免 score
     * 优惠券减免 coupon
     */
    fun loadMullaLoanPayLinkAction(){
        var httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_LOAN_REPAYMENT_URL_PATH)
        if (MullaConfigs.isUgx() || MullaConfigs.isKsh()){//肯尼亚、乌干达 需要使用 getOrderRepayH5 获取链接
            httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_LOAN_REPAYMENT_KSH_UGX_URL_PATH)
        }
        val params = JSONObject().addCommonParams().addRandomParams().apply {
            put("product",mvpView?.loadProductName())
            put("token",mvpView?.loadProductToken())
            put("mobile",SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_MOBILE))
        }
        var couponId = ""
        selectCoupon?.let{
            couponId = it.optString("id")
            params.put("annulType","coupon")
            params.put("couponId",couponId)
        }
        HttpHelper.postMullaAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                mvpView?.hideMullaLoading()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null){
                            var linkUrl = ""
                            val url = obj.optString("url")
                            if (url.isNotEmpty()){
                                linkUrl = url
                            }

                            val repayUrl = obj.optString("repayUrl")
                            if (repayUrl.isNotEmpty()){
                                linkUrl = repayUrl
                            }

                            //没有还款链接 - 需要进入还款状态页查询还款状态
                            if (linkUrl.isEmpty()){
                                val thirdOrderId = obj.optString("thirdOrderId")
                                mvpView?.showMullaPaymentStatusPage(thirdOrderId,couponId)
                            } else {
                                mvpView?.showMullaLoanPayLink(linkUrl)
                            }
                        }
                    }
                    else -> {
                        mvpView?.showMullaToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }
}